<template>
<!--  -->
<!-- 自定义组件：导航 -->
<!--  -->

<div class="top-navigation">

    <template v-if="folderList.length > 0">
        <span class="back link" @click="backParent">返回上一级</span>
        <el-divider direction="vertical"></el-divider>    <!-- | 线 -->
        <span class="link"  @click="setCurrentFolder(-1)"> 全部文件 </span>
    </template>

    <!-- <span v-if="folderList.length > 0" class="link"  @click="setCurrentFolder(-1)"> 全部文件 </span> -->
    <span v-if="folderList.length == 0" class="all-file">全部文件</span>

    <!-- 遍历 -->
    <template v-for="(item, index) in folderList">
        <span class="iconfont icon-right"></span>
        <!-- 非最后一个元素可点击 -->
        <span class="link" v-if="index < folderList.length - 1" @click="setCurrentFolder(index)"  style="width:100px">
            {{ item.fileName }}
        </span>
        <!-- 最后一个元素不可点击 -->
        <span class="text" v-if="index == folderList.length - 1">{{ item.fileName }}</span>
    </template>

</div>
  
</template>

<script setup>
import { ref, reactive, getCurrentInstance, nextTick, onMounted, watch } from "vue";
import { useRoute, useRouter } from "vue-router"
const { proxy } = getCurrentInstance();
const router = useRouter();   //用于设置值
const route = useRoute();     //用于取值

//接收父组件传递过来的参数
const props = defineProps({
    //是否监听路由（是否触发watch方法）
    watchPath: {
        type: Boolean,
        default: true,    
    },
    //外部分享
    shareId: {
        type: String,
    },
    //管理员
    adminShow: {
        type: Boolean,
        default: false,
    },
});

const api = {
    getFolderInfo: "/file/getFolderInfo",           //当前路径下的目录
    getFolderInfo4Share: "/showShare/getFolderInfo",//外部分享时
    getFolderInfo4Admin: "/admin/getFolderInfo",    //管理员时
}


//-------------------------------------------------------------------------
//变量定义
const folderList = ref([]);                  //当前绝对路径（目录集合）
const currentFolder = ref({ fileId: "0" });  //当前所在目录
const category = ref();                      //主页面左边的分类栏
//--------------------------------------------------------------------------

//初始化
const init = () => {
    folderList.value = [];
    currentFolder.value = {fileId: "0"};
    doCallback();  //刷新列表
}


//返回上一级 按钮
const backParent = () => {
    let currentIndex = null;
    for (let i = 0; i < folderList.value.length; i++) {
        if (folderList.value[i].fileId == currentFolder.value.fileId) {
            currentIndex = i;
            break;
        }
    }

    setCurrentFolder(currentIndex - 1);
}


//点击导航
const setCurrentFolder = (index) => {
    if (index == -1) {   
        //代表点的是“全部文件”
        currentFolder.value = { fileId: "0" };
        folderList.value = [];
    } else {
        //点的是导航，
        currentFolder.value = folderList.value[index];
        folderList.value.splice(index + 1, folderList.value.length);   //导航删除
    }
    setPath();
}


//打开(进入)目录 --- 由父组件/main/Main.vue中的preview方法 或 FolderSelect.vue中的selectFolder方法调用
const openFolder = (data) => {
    const { fileId, fileName } = data;     //根据属性名映射赋值给到变量
    const folder = {
        fileName: fileName,
        fileId: fileId,
    };
    folderList.value.push(folder);         //push：从数组末尾添加数据
    currentFolder.value = folder;          //更新当前所在目录
    setPath();
};

defineExpose({ openFolder });   //是Vue3中的一个新特性,它允许组件将其内部的数据和方法暴露给父组件


//改变路径（路由）
const setPath = () => {
    if (!props.watchPath) {
        //TODO 设置不监听路由回调方法
        doCallback();
        return;
    }
    //整理参数
    let pathArray = []; 
    folderList.value.forEach((item) => {  //遍历数组
        pathArray.push(item.fileId);      //push: 从数组末尾添加数据
    });
    //设置路由
    router.push({
        path: route.path,    //跳转路径为当前路径
        query: pathArray.length == 0 ? "" : { path: pathArray.join("/") },  //query: 路径的?后面接上参数 -- join: 生成一个字符串，元素之间以\分隔
    });
};


//根据路由提供的文件id串 找到对应的文件
const getNavigationFolder = async (path) => {
    let url = api.getFolderInfo;
    if (props.shareId) {
        url = api.getFolderInfo4Share;
    }
    if (props.adminShow) {
        url = api.getFolderInfo4Admin;
    }

    console.log("getNavigation..." + url);
    let result = await proxy.Request({
        url: url,
        showLoading: false,   //关闭等待响应时的样式
        params: {
            path: path,
            shareId: props.shareId,
        },
    });

    //处理返回
    if (!result) {
        return;
    }
    folderList.value = result.data.folderList;
}


//调用触发父组件方法（Main.vue或FolderSelect.vue），刷新列表
const  emit = defineEmits(["navChange"]);
const doCallback = () => {
    console.log("doCallback..." + currentFolder.value.fileId);
    emit("navChange", {
        categoryId: category.value,      //主页面左边的分类栏
        curFolder: currentFolder.value,  //当前所在目录（注：因为并未.fileId，所以值为: {fileId: "?"} ）
    })
}


//监听路由 route，路径变动时触发  (wath方法需要手动import引入)
watch(
    () => route, 
    (newVal, oldVal) => {
        if (!props.watchPath) {   //是否指定了不监听路由
            return;
        };
        //indexOf: 返回参数在字符串中首次出现的位置，无则返回-1
        if (newVal.path.indexOf("/main") === -1 && newVal.path.indexOf("/settings/fileList") === -1) { 
            return;
        }

        const path = newVal.query.path;            //newVal.query: 从url ?号后面获取path参数
        category.value = newVal.params.category;   //newVal.params: /router/index.js -- 22行 监听Main.vue页面的分类栏
        if (path == undefined) {
            init();    //并未进入目录，仅初始化刷新列表
        } else {
            //点击进入目录，重新查询列表
            console.log("watch...." + path);
            getNavigationFolder(path);   
            let pathArray = path.split("/");    //以 / 分割字符串
            currentFolder.value = { fileId: pathArray[pathArray.length - 1] }; //设置当前所在目录
            doCallback();
    
        }
    },
    { immediate: true, deep: true }
);


</script>

<style lang="scss" scoped>

.top-navigation {
    font-size: 13px;
    display: flex;
    align-items: center;
    line-height: 40px;
    .all-file {
        font-weight: bold;
    }
    .link {
        color: #06a7ff;
        cursor: pointer;
    }
    .icon-right {
        color: #06a7ff;
        padding: 0px 5px;
        font-size: 13px;
    }
}

</style>